#include "losu.h"
#include "losu_bytecode.h"
#include "losu_dump.h"
#include "losu_gc.h"
#include "losu_mem.h"
#include "losu_object.h"
#include "losu_syntax.h"
#include "losu_vm.h"

#include "stack.h"
#include "../xkit.h"
#include "collections.h"

static inline int32_t __xkit_arg_retrunAny(losu_vm_t vm, losu_object_t o) {
    stack_push(vm, *o);
    return 1;
}

/** losu-capi (self, size: number) -> self
 * @brief: "constructor of class: THISxkit_MODULEcollections_CLASSStack"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_constructor(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    if (argc < 2) {
        __error_TooFewArguments(vm);
        return 0;
    }
    StackHeader *h = NULL;
    size_t size = obj_getnum(vm, argv + 1);
    h = StackInit(vm, size);
    if (h) {
        obj_unitsetstr(vm, *argv, "__cptr__", obj_newptr(vm, h));
    }
    return __xkit_arg_retrunAny(vm, argv);
} 


/** losu-capi (self) -> number
 * @brief: "返回当前栈中元素的数量"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNCsize(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    StackHeader *h = getCPointer(vm, argv);
    return arg_returnNum(vm, h->curIndex);
}


/** losu-capi (self) -> 
 * @brief: "析构函数"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNC__del__(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    (void)argv;
    StackHeader *h = getCPointer(vm, argv);
    StackFree(vm, h);
    obj_unitsetstr(vm, *argv, "__cptr__", obj_newfalse(vm));
    return 0;
}


/** losu-capi (self) -> any
 * @brief: "弹出栈顶元素并返回"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNCpop(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    StackHeader *h = getCPointer(vm, argv);
    losu_object target;
    StackPop(vm, h, &target);
    return __xkit_arg_retrunAny(vm, &target);
}


/** losu-capi (self, item: any) -> self
 * @brief: "将元素压入栈顶"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNCpush(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    if (argc < 2) {
        __error_TooFewArguments(vm);
        return 0;
    }
    StackHeader *h = getCPointer(vm, argv);
    StackPush(vm, h, argv + 1);
    return __xkit_arg_retrunAny(vm, argv);
}


/** losu-capi (self) -> item
 * @brief: "返回栈顶元素但不弹出"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNCpeek(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    StackHeader *h = getCPointer(vm, argv);
    losu_object target;
    StackPeek(vm, h, &target);
    return __xkit_arg_retrunAny(vm, &target);
}


/** losu-capi (self) -> bool
 * @brief: "检查栈是否已满"
 */
int32_t THISxkit_MODULEcollections_CLASSStack_FUNCisFull(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    StackHeader *h = getCPointer(vm, argv);
    stack_push(vm, h->curIndex == h->length ? obj_newtrue(vm) : obj_newfalse(vm));
    return 1;
}